<template>
  <div ref="scEcharts" style="height: 100%; width: 100%"></div>
</template>

<script setup>
import {
  ref,
  onMounted,
  onUnmounted,
  watch,
  nextTick,
  computed,
  onActivated,
  markRaw
} from "vue";
import * as echarts from "echarts";
import T from "./echarts-theme-T.js";
import API from "@/api/model/meta";
import { deepClone } from "@/utils/arr.js";
echarts.registerTheme("T", T);
const unwarp = (obj) => obj && (obj.__v_raw || obj.valueOf() || obj);
const props = defineProps({
  widget: { type: Object, default: () => {} },
  fileName: { type: String, default: "" },
});
const myChart = ref(null);
const isActivat = ref(false);
const scEcharts = ref(null);
const form = ref({})
let observer = null;
// 监听窗口大小变化
const handleResize = () => {
  if (myChart.value) {
    // console.log(myChart.value)
    myChart.value.setOption(computedOptions.value,true);
    
    myChart.value.resize();
  }
};

// 绘制图表
const draw = () => {
  var chart =markRaw( echarts.init(scEcharts.value, "T"));
  chart.setOption(computedOptions.value);
  myChart.value = chart;
  // myChart.value.resize();
  window.addEventListener("resize", handleResize);
  // scEcharts.value.addEventListener('resize',handleResize)
};

// 监听widget prop的变化
watch(
  () => props.widget,
  (newValue, oldValue) => {
    if (newValue && newValue.option) {
      unwarp(myChart.value).setOption(newValue.option, true);
    }
  },
  { deep: true }
);

// 计算属性，返回widget.option或空对象
const computedOptions = computed(() => props.widget.option || {});
const changeOption = async(val)=>{
  if(val){
    form.value = val
  }
  let param = {
    fileName: props.fileName,
    chartParam: {
      datasetId: props.widget.dataset.datasetId,
      dims: props.widget.dataset.dims,
      indexs: props.widget.dataset.indexs,
    },
    fieldMap:form.value
  };
  console.log(param)
  let res = await API.chartDesigner.queryChartData.post(param);
  console.log(res)
  if (res.code == "200") {
    let option = deepClone(props.widget.option)
    option.dataset = res.data
    unwarp(myChart.value).setOption(option, true);
  }
}
// 组件挂载时绘制图表
onMounted(() => {
  isActivat.value = true;
  observer = new ResizeObserver(handleResize);
  observer.observe(scEcharts.value);
  nextTick(() => {
    draw();
  });
});

// 组件卸载时清理
onUnmounted(() => {
  isActivat.value = false;
  if (myChart.value) {
    window.removeEventListener("resize", handleResize);
    myChart.value.dispose(); // 清理图表实例
  }
  if (observer) {
    observer.disconnect();
  }
});
onActivated(() => {
  if (isActivat.value) {
    nextTick(() => {
      myChart.value.resize();
    });
  }
});
defineExpose({
  changeOption
});
</script>